<?php

/**
 * Post form.
 *
 * @package    form
 * @subpackage post
 * @version    SVN: $Id: sfPropelFormTemplate.php 6174 2007-11-27 06:22:40Z fabien $
 */
class PostForm extends BasePostForm
{
  public function configure()
  {
  	if (sfContext::getInstance()->getUser()->hasCredential('admin'))
  	{
      unset($this['datetime']);
  	}
  	else
  	{
  	  unset($this['user_id'], $this['datetime']);
  	}   
  	
  	$this->widgetSchema['file'] = new sfWidgetFormInputFile();        
    $this->validatorSchema['file'] = new sfValidatorFile(array('required' => false));
    
  	$this->widgetSchema['published'] = new sfWidgetFormInputCheckbox(array('value_attribute_value' => '1'));        
  	$this->widgetSchema['comment_allow'] = new sfWidgetFormInputCheckbox(array('value_attribute_value' => '1'));
  	
    $this->validatorSchema['published'] = new sfValidatorBoolean();
    $this->validatorSchema['comment_allow'] = new sfValidatorBoolean();
    
    $this->validatorSchema->setPostValidator(new myValidatorHandle(array('model' => 'Post', 'column' => 'handle')));
    
    $this->widgetSchema->setNameFormat('post[%s]');

    $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);
  	
    $this->embedI18n(LanguagePeer::getCulturesArray());
  	
    $decorator = new myWidgetFormSchemaFormatterDl($this->widgetSchema);
    $this->widgetSchema->addFormFormatter('dl', $decorator); 
    $this->widgetSchema->setFormFormatterName('dl');
  }
  
  public function updateObject($values = null)
  {
  	$old_file = $this->getObject()->getFile();
  	$published = $this->getObject()->getPublished();
  	
  	$object = parent::updateObject($values = null);
    
    if ($this->getValue('file'))
    {
      $filename = str_replace(sfConfig::get('sf_upload_dir').DIRECTORY_SEPARATOR, '', $object->getFile());
    
      myThumbnail::thumbnails($filename, $object, $object->getUser());
      
      // delete file
      if (file_exists($object->getFile()))
      {
      	unlink($object->getFile());
      }

      $object->setFile($filename);
    }
    else
    {
      $object->setFile($old_file);
    }
        
    if (!$object->getHandle())
    {
      $object->setCulture('en_US');
      if ($object->getTitle())
      {
        $object->setHandle(myTools::makeHandle($object->getTitle()));
      }
      else
      {   
      	$object->setHandle(md5($object->getFile()));   	
      }
    }
    
    if ($object->isNew())
    {
      $object->setDatetime(myTools::now());
    }
    elseif ($this->getValue('published') and !$published)
    {
      $object->setDatetime(myTools::now());
    }
    
    return $object;
  }
}
